<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="title"
      width="680px"
      :destroyOnClose="true"
      @register="registerModal"
      @ok="handleSubmit"
    >
      <div class="form-container">
        <div class="alert">
          <a-alert>
            <template #message>
              当前地址：<span class="text-primary" v-if="returnData.address">{{ returnData.address }}</span><span v-else>请选择地址</span>
            </template>
          </a-alert>
        </div>
        <div class="search-wrapper">
          <div class="search-inner">
            <div class="input-field">
              <a-row :gutter="6">
                <a-col :span="8">
                  <a-select v-model:value="searchType" @change="handleSearchTypeChange">
                    <a-select-option value="1">按地址搜索</a-select-option>
                    <a-select-option value="2">按坐标搜索</a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="16">
                  <a-input-search 
                    allowClear 
                    id="search" 
                    v-model:value="searchKey"
                    enter-button="搜索"
                    @search="handleSearch"
                  />
                  <div class="tip-box beauty-scroll" id="searchTip"></div>
                </a-col>
              </a-row>
              <a-input-group compact>
                
                
              </a-input-group>
            </div>
            <a-button class="reset" type="link" @click="resetMap">重置</a-button>
          </div>
        </div>
        <div class="map-container">
          <div id="mapContainer" class="map"></div>
        </div>
      </div>
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
import { ref, h, onUnmounted, defineEmits } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader';
import { AutoComplete } from 'ant-design-vue'
import { ContactsOutlined } from '@ant-design/icons-vue'
import { isEmpty, isEmptyExt } from '/@/utils/is';
import {BasicModal, useModal, useModalInner} from '/@/components/Modal';
import edAddressSelect from './edAddressSelect.vue';

const title = ref('选择地址');
let searchType = ref('1');
let searchKey = ref('');
const map = ref(null);
let marker = ref(null);
let adcode = ref('');
let returnData = ref({
  address: '',
  lat: 0,
  lng: 0,
  adcode: '',
  area: ''
});
const emit = defineEmits(['register','success']);
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  console.log("modal data",data);
  initMap();
});

onUnmounted(() => {
  if(map.value != null){
    //map.value.destroy();
  }
})

window._AMapSecurityConfig = {
  securityJsCode:'1ac8b0d0d8b4af7c4c438d32fbfa0fd3',
}
function initMap(){
  console.log("initMap", map.value);
  AMapLoader.reset();
  AMapLoader.load({
    key: 'de00ded4c4d62fb7515bbfcae3542fc7', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.PlaceSearch'] // 需要使用的插件列表，如比例尺'AMap.Scale'等
  }).then((AMap) => {
    console.log("AMap:", AMap);
    map.value = new AMap.Map('mapContainer', {
      resizeEnable: true,
      zoom:11,
      //center: [116.397428, 39.90923]
    });
    //地图点击获取地址
    evClickGetAddress();
    // 在合适的地方创建 PlaceSearch 实例
    AMap.plugin(['AMap.PlaceSearch','AMap.AutoComplete'], function(){
      let ac = new AMap.AutoComplete({input:'search'});
      let placeSearch = new AMap.PlaceSearch({
        extensions:'all',
        autoFitView: true,
      })
      ac.on("select", function(e){
        console.log("ac select:",e);
        placeSearch.setCity(e.poi.adcode);
        placeSearch.search(e.poi.name, function(status, result){
          console.log("placeSearch:",result);
          if(status === 'complete' && result.info === 'OK'){
            let {pois} = result.poiList, poi = pois[0];
            searchKey.value = poi.pname + ((poi.cityname=='上海市'||poi.cityname=='重庆市'||poi.cityname=='天津市'||poi.cityname=='北京市')?'':poi.cityname) + poi.adname + poi.address;
            adcode.value = poi.adcode;
            let lnglat = {lng:poi.location.lng, lat:poi.location.lat};
            let data = Object.assign(lnglat, {
                adcode: adcode.value,
                address: searchKey.value,
                area: poi.pname + ((poi.cityname=='上海市'||poi.cityname=='重庆市'||poi.cityname=='天津市'||poi.cityname=='北京市')?'':poi.cityname) + poi.adname
            });
            addMarker(data);
          }
        });
      });
    });
  })
}

function evClickGetAddress(){
  let mapV = map.value;
  mapV.on("click", function(ev){
    let lnglat = [ev.lnglat.lng, ev.lnglat.lat], pt = {lng:ev.lnglat.lng, lat:ev.lnglat.lat};
    AMap.plugin('AMap.Geocoder', function(){
      let geocoder = new AMap.Geocoder();
      geocoder.getAddress(lnglat, function(status, result){
        console.log("AMap.Geocoder:",status, result);
        if(result.info === 'OK'){
          let {regeocode} = result;
          let data = Object.assign(pt, {
              address: regeocode.formattedAddress,
              adcode: regeocode.addressComponent.adcode,
              province: regeocode.addressComponent.province,
              city: (regeocode.addressComponent.province.indexOf('北京')>-1 || regeocode.addressComponent.province.indexOf('上海')>-1 || regeocode.addressComponent.province.indexOf('天津')>-1 || regeocode.addressComponent.province.indexOf('重庆')>-1) ? regeocode.addressComponent.province : regeocode.addressComponent.city,
              district: regeocode.addressComponent.district,
              area: regeocode.addressComponent.province + regeocode.addressComponent.city + regeocode.addressComponent.district,
          })
          addMarker(data);
        }
      })
    });
  })
}

function addMarker(data){
  let mapV = map.value, markerV = marker.value;
  if(markerV != null){
    mapV.remove(markerV);
  }
  marker.value = new AMap.Marker({
    position: new AMap.LngLat(data.lng, data.lat),
    map: mapV
  });
  mapV.add(marker.value);
  mapV.setZoomAndCenter(12, new AMap.LngLat(data.lng, data.lat));
  console.log("addMarker", data);
  returnData.value = Object.assign(returnData.value, data, {
    lng: data.lng,
    lat: data.lat,
  });
}

function handleSearch(value:string){
  console.log("handleSearch", value);
  if(searchType.value == '1'){
    AMap.plugin('AMap.Geocoder', function(){
      let params = {};
      if(isEmptyExt(adcode.value)){
        params = {city: adcode.value}
      }
      let geocoder = new AMap.Geocoder(params);
      geocoder.getLocation(value, function(status, result){
        console.log("geocoder:", status, result);
        if (status === 'complete' && result.info === 'OK') {
          let geocoder = result.geocodes[0];
          let pt = {lng:geocoder.location.lng, lat:geocoder.location.lat};
          let data = Object.assign({}, pt, {
              address: geocoder.formattedAddress,
              adcode: geocoder.adcode,
              province: geocoder.addressComponent.province,
              city: (geocoder.addressComponent.province.indexOf('北京')>-1 || geocoder.addressComponent.province.indexOf('上海')>-1 || geocoder.addressComponent.province.indexOf('天津')>-1 || geocoder.addressComponent.province.indexOf('重庆')>-1)? geocoder.addressComponent.province : geocoder.addressComponent.city,
              district: geocoder.addressComponent.district,
              area: geocoder.addressComponent.province + geocoder.addressComponent.city + geocoder.addressComponent.district,
          })
          addMarker(data);
        }
      });
    })
  }else if(searchType.value == '2'){
    let lnglat = [], lng = 0, lat = 0;
    lng = Number(value.split(",")[0]), lat = Number(value.split(",")[1]);
    lnglat = [new AMap.LngLat(lng, lat)];
    AMap.plugin('AMap.Geocoder', function(){
      let geocoder = new AMap.Geocoder();
      geocoder.getAddress(lnglat, function(status, result){
        if(result.info === 'OK'){
          let data = {};
          if(searchType.value == 1){
              let {regeocode} = result;
              data = Object.assign(lnglat, {
                  address: regeocode.formattedAddress,
                  adcode: regeocode.addressComponent.adcode
              });
          }else if(searchType.value == 2){
              let {regeocodes} = result;
              data = Object.assign({lng:value.split(",")[0], lat:value.split(",")[1]}, {
                  address: regeocodes[0].formattedAddress,
                  adcode: regeocodes[0].addressComponent.adcode
              });
          }
          addMarker(data);
        }
      });
    });
    addMarker({lng: value, lat: value});
  }
}

function resetMap(){
  console.log("resetMap");
}
function handleSearchTypeChange(value){
  console.log("handleSearchTypeChange",value);
}
function handleSubmit() {
  console.log("handleSubmit", returnData.value);
  emit('success', returnData.value);
  closeModal();
}
</script>
<style lang="less" scoped>
.form-container {
  padding:15px;
  .search-wrapper {
    padding:10px 0;
    .search-inner {
      display:flex; justify-content:flex-start; align-items:center;
      .input-field {
        margin-right:10px; min-width:70%;
      }
    }
  }
  .map-container {
    height:400px;
    .map {
      width:100%; height:100%;
    }
  }
}
.text-primary {
  color:@primary-color;
}
</style>
